<form id="editMacroTableForm" lay-filter="editMacroTableForm" class="layui-form model-form">
    <input name="userId" type="hidden"/>
    <div class="layui-form-item">
        <label class="layui-form-label">名称</label>
        <div class="layui-input-block">
            <input name="name" placeholder="请输入名称" type="text" class="layui-input" maxlength="20"
                   lay-verType="tips" lay-verify="required" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">编码</label>
        <div class="layui-input-block">
            <input name="code" placeholder="请输入编码" type="text" class="layui-input" maxlength="20"
                   lay-verType="tips" lay-verify="required" />
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">对象分类</label>
        <div class="layui-input-block">
            <select name="meta_type" placeholder="请选择" id="addclass_meta_type_box" lay-verify="required" >

            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">数据格式</label>
        <div class="layui-input-block">
            <select name="data_format" placeholder="请选择" id="data_format_box" lay-verify="required" >

            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">报告期类型</label>
        <div class="layui-input-block">
            <select name="report_type" placeholder="请选择" id="report_type_box">

            </select>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">报送开始时间</label>
        <div class="layui-input-block">
            <input name="start_time" type="text" class="layui-input" id="startTime" placeholder="yyyy-MM-dd HH:mm:ss">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">报送结束时间</label>
        <div class="layui-input-block">
            <input name="end_time" type="text" class="layui-input" id="endTime" placeholder="yyyy-MM-dd HH:mm:ss">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">报送地点</label>
        <div class="layui-input-block">
            <input name="locale_of_submission" placeholder="请输入报送地点" type="text" class="layui-input" maxlength="20"
                   lay-verType="tips" lay-verify="required" required/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">数据来源</label>
        <div class="layui-input-block">
            <input name="source_type" placeholder="请输入数据来源" type="text" class="layui-input" maxlength="20"
                   lay-verType="tips" lay-verify="required" required/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">排序</label>
        <div class="layui-input-block">
            <input name="sort" placeholder="请输入排序" type="text" class="layui-input" maxlength="20"
                   lay-verType="tips" lay-verify="required" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">所属目录</label>
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" id="par_menu_name">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</button>
            <ul id="editcatalogTree" class="ztree" ></ul>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">是否支持多版本数据导入</label>
        <div class="layui-input-block">
            <input type="checkbox" name="datav_is_multi" lay-skin="switch" lay-text="是|否">
        </div>
    </div>
    <div class="layui-form-item text-right">
        <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" ew-event="closePageDialog">取消</button>
        <button class="layui-btn layui-btn-sm" lay-filter="addClassFormSubmit" lay-submit >确定</button>
    </div>
</form>

<script type="text/tmpl" id="data_format-tmpl">
    {{ each data_format}}
    <option value="{{$value.value}}">{{$value.name}}</option>
    {{/each}}
</script>

<script type="text/tmpl" id="addclass_meta_type-tmpl">
    {{ each records}}
    <option value="{{$value.code}}">{{$value.name}}</option>
    {{/each}}
</script>

<script type="text/tmpl" id="report_type-tmpl">
    {{ each data}}
    <option value="{{$value.value}}">{{$value.key}}</option>
    {{/each}}
</script>

<script>
    $("#editcatalogTree").hide();
    //获取权限方法
    var userInfo = getAuthority();
    layui.use(['layer', 'form', 'admin','tree','laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var tree = layui.tree;
        var laydate = layui.laydate;
        var Authorization;//请求接口用
        var tableCatalog = window.tableCatalog;
        var selectedTable = window.selectedTable;
        var edit_par_id = selectedTable.parId;//所属目录ID
        var setting={//树设置
            catalogTreeSetting:{//原点区划树设置-区划变更弹窗使用
                edit: {
                    enable: true,
                    showRemoveBtn: false,
                    showRenameBtn: false,
                    drag: {
                        isCopy: true,
                        isMove: false,
                        prev: false,
                        next: false,
                        inner: false
                    }
                },
                data: {
                    key: {
                        children: "sub"
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onExpand: onExpandCatalogTree,
                    onClick: zTreeCatalogOnClick
                },
                view: {
                    showIcon: true,
                    showLine: true
                }
            }
        }
        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;
            init();
        }

        function init(){
            getTableClassifyList();
            getSelectReports();
            var str = template("data_format-tmpl",macroUrl.config);
            document.getElementById("data_format_box").innerHTML = str;         
            $("#par_menu_name").text(selectedTable.menuName);
            $("#par_menu_name").click(function () {
                $("#editcatalogTree").show();
                lazyLoadCatalogTree();
            });
            
            //日期时间选择器
            laydate.render({
                elem: '#startTime'
                ,type: 'datetime'
            });

            laydate.render({
                elem: '#endTime'
                ,type: 'datetime'
            });
            form.render('checkbox');
            form.render('select');

            var selectedTable_new = strAllReplaceLine(selectedTable);
            if(selectedTable_new.datav_is_multi){
                selectedTable_new.datav_is_multi=true; //开关状态
            }
            form.val("editMacroTableForm",selectedTable_new)

            // 表单提交事件
            form.on('submit(addClassFormSubmit)', function (data) {
                var formdata = data.field;
                let req = {
                    code:formdata.code,
                    data_format:formdata.data_format,
                    end_time:formdata.end_time,
                    locale_of_submission:formdata.locale_of_submission,
                    meta_type:formdata.meta_type,
                    name:formdata.name,
                    par_id:edit_par_id,
                    report_type:formdata.report_type,
                    sort:formdata.sort,
                    source_type:formdata.source_type,
                    start_time:formdata.start_time,
                    datav_is_multi:formdata.hasOwnProperty('datav_is_multi')? 1:0,
                    id:selectedTable_new.id,
                    version:selectedTable_new.version
                }
                axios({
                    method: 'PUT',
                    url:macroUrl.table.editTable,
                    data:$.param(req),
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (response) {
                        if(response.status == 200 &&response.data.message == "success"){
                            layer.msg("编辑成功", {icon: 1});
                            window.editTableStatus = true;
                            admin.closeDialog('#editMacroTableForm');  // 关闭页面层弹窗
                        }else{
                            layer.msg(response.data.message, {icon: 2});
                        }
                        layer.closeAll('loading');
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    });
                return false;
            });
        }

        // 对象分类
        function getTableClassifyList() {
            var req={
                current: 1,
                size: 100
            };
            axios.get(metadataUrl.tableClassify.tableClassifyList,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data.data;
                        var str = template("addclass_meta_type-tmpl",data);
                        document.getElementById("addclass_meta_type_box").innerHTML = str;                        
                        //对象分类不允许修改
                        if(selectedTable.id){
                            $("#addclass_meta_type_box").attr("disabled",true);
                        }
                        $("#addclass_meta_type_box").val(selectedTable.metaType);
                        form.render('select');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        //获取报告期类型
        function getSelectReports(){
            axios({
                method: 'get',
                url:metadataUrl.tableClassify.reportTableClassify,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var data = response.data;                                              
                        var str = template("report_type-tmpl",data);                        
                        document.getElementById("report_type_box").innerHTML = str;
                        //报告期不允许修改
                        if(selectedTable.id){
                            $("#report_type_box").attr("disabled",true);
                        }
                        $("#report_type_box").val(selectedTable.reportType);
                        form.render('select');
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
        }

        /*将js对象属性名转换为下划线*/
        function strAllReplaceLine(new_obj){
            let arr = [];
            var result = strAllReplace(new_obj);
            return result;
            function strReplace(str) {
                const UP_CASE_REG =/[A-Z]/g;
                const NUMBER_REG=/[A-Za-z][\d]/g
                let newstr = ""
                getIndex(UP_CASE_REG, str)
                getIndex(NUMBER_REG, str)
                arr.sort((a,b)=> a-b )
                for(let i = 0;i < arr.length; i ++) {
                    if(i === 0) {
                        newstr += str.slice(0,arr[i]) + "_"
                    }
                    else {
                        newstr += str.slice(arr[i-1],arr[i]) + "_"
                    }
                }
                newstr += str.slice(arr[arr.length-1])
                return newstr.toLowerCase()
            }
            function getIndex(reg, str) {
                do{
                    reg.test(str)
                    if(reg.lastIndex !== 0 && reg.lastIndex-1 !== 0){//reg.lastIndex-1 !== 0判断首字母是否大写
                        arr.push(reg.lastIndex-1)
                    }
                }while(reg.lastIndex > 0)
            }

            function strAllReplace(obj) {
                let newObj = {}
                Object.entries(obj).forEach(([key, value]) =>
                {
                    newObj[strReplace(key)] = value
                    arr = []
                })
                return newObj
            }
        }

        //懒加载目录树
        function lazyLoadCatalogTree() {
            var req={
                parent_id : 'root',
            };
            axios.get(macroUrl.catalog.catalogTree,{
                params: req,
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.status == 200 &&response.data.message == "success"){
                        var datas = response.data.data;
                        if (datas.length > 0) {
                            for (const row of datas) {
                                row.isParent = true;
                                row.sub = []; //存放子节点
                                row.drag = true;
                            }
                        }
                        var dataarr = [{"data_type":0,
                            "id":"root",
                            "name":"根目录",
                            "par_id":"",
                            "version":"0",
                            "sub":datas
                        }];
                        var treeObj = $.fn.zTree.init($("#editcatalogTree"), setting.catalogTreeSetting, dataarr);
                        var nodes = treeObj.getNodes();
                        console.log(nodes)
                        if (nodes.length>0) {
                            treeObj.expandNode(nodes[0], true, true, true);
                        }

                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });

        }

        //展开树
        function onExpandCatalogTree(event, treeId, treeNode) {
            if(treeNode.sub.length==0){
                var req={
                    parent_id : treeNode.id,
                };
                axios.get(macroUrl.catalog.catalogTree,{
                    params: req,
                    headers:{
                        'Authorization':Authorization
                    }
                })
                    .then(function (response) {
                        if(response.status == 200 &&response.data.message == "success"){
                            var datas = response.data.data;
                            if (datas.length > 0) {
                                for (const row of datas) {
                                    row.isParent = true;
                                    row.sub = []; //存放子节点
                                    row.drag = true;
                                }
                            }
                            const treeObj = $.fn.zTree.getZTreeObj("editcatalogTree");
                            treeObj.addNodes(treeNode, datas);
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                        if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                            // 进行重新登陆
                            localStorage.clear();
                            top.location.href=loginPageUrl;
                        }
                    });
            }

        }

        //树节点选中事件
        function zTreeCatalogOnClick(event, treeId, treeNode) {
            edit_par_id = treeNode.id;
            $("#par_menu_name").text(treeNode.name);
            $("#editcatalogTree").hide();
        }

    });
</script>